package com.apex.gateway.config;

import cn.dev33.satoken.reactor.filter.SaReactorFilter;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.apex.gateway.properties.SecurityProperties;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;

/**
 * [Sa-Token 权限认证] 配置类
 *
 * @author MoNaiHui
 */
@Configuration
public class SaTokenConfigure {

    @Resource
    private SecurityProperties securityProperties;

    // 注册 Sa-Token全局过滤器 
    @Bean
    public SaReactorFilter getSaReactorFilter() {
        return new SaReactorFilter()
                // 拦截地址
                .addInclude("/**")
                // 开放地址
                .setExcludeList(Arrays.asList(securityProperties.getExcludes()))
                .setAuth(obj  -> {
                    // 登录校验 -- 拦截所有路由 用于开放登录
                    SaRouter.match("/**").check(r -> StpUtil.checkLogin());
                })
                // 异常处理方法：每次setAuth函数出现异常时进入
                .setError(e -> {
                    return SaResult.error(e.getMessage());
                });
    }
}